package com.bluelight.expertsystemmobile.versionupdate.action;

import java.io.File;
import java.util.List;

import org.apache.commons.configuration.PropertiesConfiguration;
import org.apache.commons.io.FileUtils;
import org.apache.struts2.ServletActionContext;
import org.apache.struts2.convention.annotation.Action;
import org.apache.struts2.convention.annotation.Namespace;
import org.apache.struts2.convention.annotation.ParentPackage;
import org.apache.struts2.convention.annotation.Result;
import org.apache.struts2.json.annotations.JSON;
import org.springframework.beans.factory.annotation.Autowired;

import com.bluelight.expertsystemmobile.versionupdate.dao.VersionDao;
import com.bluelight.expertsystemmobile.versionupdate.entity.Version;

import support.action.BaseAction;
import support.entity.Pagination;

@ParentPackage(value = "json-default")
@Namespace("/")
@Action(value = "/versionManage", results = { @Result(name = "json", type = "json"), @Result(name = "success", location = "/index.jsp") })
public class VersionManageAction extends BaseAction {

	private static final long serialVersionUID = 1L;

	@Autowired
	private VersionDao versionDao;

	private Version version;

	public void setVersion(Version version) {
		this.version = version;
	}

	protected Pagination pagination = new Pagination();

	@JSON
	public Pagination getPagination() {
		return pagination;
	}

	public void setPagination(Pagination pagination) {
		this.pagination = pagination;
	}

	@JSON
	public Version getVersion() {
		return version;
	}

	public String getMsg() {
		return msg;
	}

	@Override
	public String execute() throws Exception {
		return "success";
	}

	public String list() throws Exception {
		List<Version> versionList = versionDao.queryVersionList(pagination);
		int total = versionDao.fetchVersionTotal();
		pagination.setList(versionList);
		pagination.setTotal(total);
		return JSON;
	}

	public String add() throws Exception {
		if (versionDao.add(version) == 1) {
			msg = "添加成功";
		} else {
			msg = "添加失败";
		}
		return JSON;
	}

	public String delete() throws Exception {
		PropertiesConfiguration p = new PropertiesConfiguration("upload.properties");
		String uploadPath = p.getString("upload.apk.path");
		String path = ServletActionContext.getRequest().getRealPath(uploadPath);
		List<Version> versions = versionDao.queryVersionListByIds(version.getId());
		for (Version v : versions) {
			String filename = v.getFileName();
			File file = new File(path + File.separator + filename);
			if (file.isFile() && file.exists()) {
				FileUtils.forceDelete(file);
			}
		}

		if (versionDao.delete(version.getId()).length > 0) {
			msg = "删除成功";
		} else {
			msg = "删除失败";
		}
		return JSON;
	}

	public String view() throws Exception {
		version = versionDao.queryVersionById(version.getId());
		return JSON;
	}
}
